﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using CreditAgricole.Framework;

namespace CreditAgricole.CommonElements.Event_Receivers.KnowledgeUnapprovedEventReceivers
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class KnowledgeUnapprovedEventReceivers : SPItemEventReceiver
    {
       /// <summary>
       /// An item was added
       /// </summary>
       public override void ItemAdded(SPItemEventProperties properties)
       {
           base.ItemAdded(properties);

           bool currentFiringStatus = this.EventFiringEnabled;

           try
           {
               this.EventFiringEnabled = false;
               properties.ListItem[SPCreditAgricoleFieldId.Title] = properties.ListItem[SPBuiltInFieldId.FileLeafRef]; // Title is the filename by default
               properties.ListItem.SystemUpdate();
           }
           catch (Exception ex)
           {
               if (!string.IsNullOrEmpty(ex.Message)) CALoggingHelper.AddErrorEntry(ex.Message);
           }
           finally
           {
               this.EventFiringEnabled = currentFiringStatus;
           }
       }

       /// <summary>
       /// An item was updated
       /// </summary>
       public override void ItemUpdated(SPItemEventProperties properties)
       {
           base.ItemUpdated(properties);

           // Start WF if Submit is checked, then uncheck it
           bool currentFiringStatus = this.EventFiringEnabled;
           try
           {
               this.EventFiringEnabled = false;
               if (properties.ListTitle.ToLower() == Constants.KnowledgeUnapprovedListTitle.ToLower())
               {
                   bool? resubmit = properties.ListItem[SPCreditAgricoleFieldId.ResubmitWorkflow] as bool?; // Get Submit WF value
                   if (resubmit == true)
                   {
                       // Start workflow
                       SPHelper.StartWorkflow(properties.ListItem, true, 0);

                       //// Reset checkbox for submit
                       //properties.ListItem[SPCreditAgricoleFieldId.ResubmitWorkflow] = false;
                       //properties.ListItem.SystemUpdate();
                   }
               }
           }
           catch (Exception ex)
           {
               if (!string.IsNullOrEmpty(ex.Message)) CALoggingHelper.AddErrorEntry(ex.Message);
           }
           finally
           {
               this.EventFiringEnabled = currentFiringStatus;
           }
       }
    }
}
